<template>
  <div v-loading="pageLoading" class="app-container flex-col"
    style="width: 100%; height: 100%; padding: 0; overflow-x:hidden">
    <div style="padding: 15px;">
      <el-row :gutter="30">
        <el-col :span="12">
          <emp-scan :focus.sync="empFocus" :data="initData" @onClear="checkData" @onChange="checkData"></emp-scan>
        </el-col>
        <el-col :span="6" :offset="6">
          <el-form>
            <el-form-item label="自动拼板数量" class="mb-0">
              <el-input-number :min="2" v-model="initData.puzzleNum" @change='puzzleNumChange' ref="puzzleNum">
              </el-input-number>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <div style="padding: 15px;border-top: 1px #606266 solid;">
      <el-row :gutter="40" class="flex">
        <el-col :span="12" style="display: flex;align-items: center;align-self: center;">
          <span style=" margin-right: 10px; font-size: 26px;">请扫码</span>
          <el-input v-model="scanData" ref="scan" size="large" style="flex: 1; font-size: 28px; font-weight: bold;"
            :disabled="!canScan" @keyup.enter.native="afterScan"></el-input>
        </el-col>

      </el-row>
    </div>
    <div class="flex1 flex" style="border-top: 1px #606266 solid; overflow: auto;">
      <div class="z-panel" style="width: 100%; padding: 15px; border-right: 1px #606266 solid;">
        <div class="flex" style="margin: 0 auto 20px">
          <div class="z-panel-title mr-30">已扫描序号
            {{ snHistory.length ? snHistory.length : '' }}
          </div>
          <el-button type="info" size="medium" @click='doPuzzle' v-if="snHistory.length > 1 ">拼板
          </el-button>
        </div>
        <div class="z-panel-body">
          <el-tag v-for="(i,t) in snHistory" type="success" :key="t" style="margin:0 10px 10px 0">{{ i.serial_number }}
          </el-tag>
          <div class="z-border z-empty-box" v-show="!snHistory.length">暂无数据</div>
        </div>
      </div>
    </div>
    <message-box :msgs="msgs"></message-box>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import _ from 'lodash'
import empScan from '@/components/WinClient/empScan'
import messageBox from '@/components/WinClient/messageBox'
import mixinClient from '@/views/_common/mixinClient'
export default {
  components: { empScan, messageBox },
  mixins: [mixinClient],
  name: 'smtBind',
  data() {
    return {
      canScan: false,
      pageLoading: false,
      empFocus: false,
      scanData: null,
      initData: {
        puzzleNum: null,
        emp: null,
        empName: null,
      },
      snHistory: [],
      msgs: [],
    }
  },
  methods: {
    checkData() {
      if (!this.initData.emp) {
        this.showMessage('请扫描作业员')
        this.empFocus = true
        return
      }
      if (this.initData.emp && !this.initData.empName) {
        this.showMessage('作业员错误', true)
        return
      }
      if (this.initData.puzzleNum) {
        this.canScan = true
        setTimeout(() => {
          this.showMessage('请扫描序号', false)
          this.$refs.scan.focus()
        }, 200)
      } else {
        this.$refs.puzzleNum.select()
        this.showMessage('请设置拼板数量')
      }
    },
    setLocaSt() {
      localStorage.setItem(`${this.functionName}-initData`, JSON.stringify({ puzzleNum: this.initData.puzzleNum }))
    },
    getLocaSt() {
      var tmp = localStorage.getItem(`${this.functionName}-initData`)
      if (tmp) {
        this.initData = JSON.parse(tmp)
        this.$refs.scan.focus()
      }
    },
    puzzleNumChange() {
      this.canScan = true
      setTimeout(() => {
        this.$refs.scan.focus()
      }, 200)
      this.setLocaSt()
    },
    afterScan() {
      this.scanData = this.scanData.trim()
      if (!this.scanData) {
        this.showMessage('没有扫描到任何内容', true)
        return
      }
      if (this.scanData.toUpperCase() == 'UNDO') {
        this.undo()
        return
      }
      if (this.scanData.toUpperCase() == 'END') {
        if (this.snHistory.length > 1) {
          this.doPuzzle()
        } else {
          this.showMessage('拼版数量需要大于1', true)
        }

        return
      }
      if (
        this.snHistory.length &&
        _.findIndex(this.snHistory, (i) => i.serial_number.toUpperCase() === this.scanData.toUpperCase()) > -1
      ) {
        this.showMessage('扫描重复，请检查', true)
        setTimeout(() => {
          this.$refs.scan.select()
        }, 200)
        return
      }
      this.pageLoading = true
      this.$request(this.$api.bindsn + 'GetSnBindData', { sn: this.scanData }, 'get', true)
        .then((r) => {
          this.pageLoading = false
          if (r) {
            if (this.snHistory.some((x) => x.mo_no.toUpperCase() != r.sn_data.mo_no.toUpperCase())) {
              this.showMessage('扫描序号，工单不一致', true)
              setTimeout(() => {
                this.$refs.scan.select()
              }, 200)
              return
            }
            if (r.sn_data.bind_status == 1) {
              this.showMessage(`[${r.sn_data.serial_number}] 已拼板，无法再拼板`, true)
              setTimeout(() => {
                this.$refs.scan.select()
              }, 200)
              return
            }
            if (r.sn_data.bind_status == 2) {
              this.showMessage(`[${r.sn_data.serial_number}] 已分板，无法再拼板`, true)
              setTimeout(() => {
                this.$refs.scan.select()
              }, 200)
              return
            }
            if (r.sn_data.sn_status === 1) {
              if (r.sn_data.hold_flag !== 'Y') {
                if (_.findIndex(this.snHistory, (i) => i.group_id !== r.sn_data.group_id) == -1) {
                  if (_.findIndex(this.snHistory, (i) => i.next_station !== r.sn_data.next_station) == -1) {
                    this.snHistory.push(r.sn_data)
                    if (this.snHistory.length == this.initData.puzzleNum) {
                      setTimeout(() => {
                        this.doPuzzle('auto')
                      }, 400)
                    }
                    this.scanData = null
                    this.showMessage('扫描成功，请继续扫描', false)
                  } else {
                    this.showMessage(`序号[${r.sn_data.serial_number}] 指站状态不一致，请检查`, true)
                    setTimeout(() => {
                      this.$refs.scan.select()
                    }, 200)
                  }
                } else {
                  this.showMessage(`序号[${r.sn_data.serial_number}] 过站状态不一致,请检查`, true)
                  setTimeout(() => {
                    this.$refs.scan.select()
                  }, 200)
                }
              } else {
                this.showMessage(`序号[${r.sn_data.serial_number}] 已被品质拦截`, true)
                setTimeout(() => {
                  this.$refs.scan.select()
                }, 200)
              }
            } else {
              this.showMessage(`[${r.sn_data.serial_number}] 已包装，无法再拼板`, true)
              setTimeout(() => {
                this.$refs.scan.select()
              }, 200)
            }
          } else {
            this.pageLoading = false
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
            this.showMessage(e.message, true)
          }
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    doPuzzle(flag) {
      this.pageLoading = true
      let list = this.snHistory.map((i) => {
        return i.serial_number
      })
      this.$request(
        this.$api.bindsn + 'BindSnCommit',
        {
          snList: list,
          emp: this.initData.emp,
        },
        'post',
        true,
      )
        .then((r) => {
          this.pageLoading = false
          if (r == '') {
            if (flag == 'auto') {
              this.showMessage('自动拼板成功', false)
            } else {
              this.showMessage('拼板成功', false)
            }
            this.scanData = null
            this.snHistory = []
          } else {
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
          }
        })
        .catch((e) => {
          this.pageLoading = false
          this.showMessage(e.message, true)
        })
    },
    undo() {
      this.scanData = null
      this.snHistory = []
      this.showMessage('重置OK，请重新扫描', false)
    },
    // showMessage(text, isError) {
    //   this.msgs.unshift({ text: dayjs().format('HH:mm:ss') + ': ' + text, type: isError ? 'error' : 'success' })
    // },
  },
  mounted() {
    this.getLocaSt()
    if (!this.initData.emp) {
      this.showMessage('请扫描作业员', false)
      this.empFocus = true
      return
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/styles/client.scss';
</style>